<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\video\model;

use think\Model;

/**
 * 视频模型
 * @package app\user_center\model
 */
class VideoPlay extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'xm_video_play';

    public static function init(){
        self::event('after_insert', function ($user) {
            
        });
        self::event('after_delete', function ($user) {
            //更新用户 作品数-1
            model('user_center/UcMemberCount', 'model\user') -> decWorkTimes($user->uid);
        });
    }

    // 定义全局的查询范围
    protected function base($query)
    {
        $query->where('play_status', 1);
    }

    /* public function getPlayOperationStatusAttr($value){
        $status = [0=>'待审核',1=>'已通过',2=>'已拒绝',3=>'上传中'];
        return $status[$value];
    } */

    public function getPlayOperationStatus($value){
        $status = [0=>'待审核',1=>'已通过',2=>'已拒绝',3=>'上传中'];
        return $status[$value];
    }

    public function getIsOriginal($value){
        $status = [0=>'转载',1=>'原创'];
        return $status[$value];
    }

    public function getIsRecommend($value){
        $status = [0=>'否',1=>'是'];
        return $status[$value];
    }

    public function getPlayType($value){
        $status = [1=>'精华版',2=>'完整版',3=>'系统视频'];
        return $status[$value];
    }

    public function getDefinitionAttr($value){
        $status = ['FD'=>'流畅', 'LD'=>'标清', 'SD'=>'高清', 'HD'=>'超清', 'OD'=>'原画', '2K'=>'2K', '4K'=>'4K'];
        return $status[$value];
    }

    /**
     * 添加数据
     * @param uid string 用户id
     * @param video_id string 视频id
     * @param main_title string 视频标题
     * @param sub_title string 副标题
     * @param description string 描述
     * @param play_type int 视频类型 1短视频 2长视频 3测试视频
     * @param is_immerse int 是否可沉浸
     * @param is_rotate int 是否可旋转
     * @param cover_url string 视频封面
     * @param is_rotate int 是否可旋转
     * @param file_size int 文件大小
     * @author jason wang <120907037@qq.com>
     * @return array_out(code, message, (int)id)
     */
    public function addData($uid, $video_id, $main_title = '', $sub_title ='', $description='', $play_type='', $is_immerse=0, $is_rotate=0, $cover_url='', $file_size='', $video_classid='', $class_tage='', $is_original=0, $father_play_id =0, $play_operation_status = 3){
         //会员主表
         $data['uid']  	= $uid;
         $data['video_id']        	= $video_id;
         if($main_title) $data['main_title']  	= $main_title;
         if($sub_title) $data['sub_title'] 	= $sub_title;
         if($description) $data['description']  = $description;
         if($play_type) $data['play_type']   		= $play_type;
         if($is_immerse) $data['is_immerse'] 		= $is_immerse;
         if($is_rotate) $data['is_rotate'] 		= $is_rotate;
         if($is_original) $data['is_original'] 		= $is_original;
         if($cover_url) $data['cover_url'] 		= $cover_url;
         if($video_classid) $data['video_classid'] 		= $video_classid;
         if($class_tage) $data['class_tage'] 		= $class_tage;
         if($father_play_id) $data['father_play_id'] 		= $father_play_id;
         $data['play_status'] 		= 1;
         $data['play_operation_status'] 		= $play_operation_status;
         $res1 = $this -> isUpdate(false) ->data($data, true) -> save();//添加  thinkphp主键bug
        
        if($res1){
            return array_out(200, 'success', $this->id);
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	/**
     * 编辑数据
     * @param play_id int 视频id
     * @param main_title string 视频标题
     * @param description string 描述
     * @param play_type int 视频类型 1短视频 2长视频 3测试视频
     * @param is_immerse int 是否可沉浸
     * @param is_rotate int 是否可旋转
     * @param is_original int 是否原创
     * @param is_recommend int 是否首页推荐
     * @author shiqiang
     * @return array_out(code, message)
     */
    public function editData($play_id, $main_title, $description,$cover_url, $play_type, $is_immerse, $is_rotate, $play_status = 1, $is_recommend = 0, $is_original, $video_classid, $customLabel='', $play_operation_status=null){
        $data['main_title']   	= $main_title;
        $data['description']  	= $description;
        if(!empty($cover_url)) $data['cover_url']  	= $cover_url;
        //if($play_type) $data['play_type']   	= $play_type;//视频类型不能改
        $data['is_immerse']   	= $is_immerse;
        $data['is_rotate']   	= $is_rotate;
        $data['is_original']   	= $is_original;
        $data['is_recommend']   = $is_recommend;
        $data['video_classid']  = $video_classid;
        $data['play_status']  	= $play_status;
        if($play_operation_status >= 0) $data['play_operation_status']  	= $play_operation_status;
        $play_id_list[] = $play_id;
        //判断视频是否存在 父亲id 或者儿子id
        $father_play_info1 = $this->find($play_id);//dump($father_play_info1);
        if(isset($father_play_info1) && $father_play_info1->father_play_id > 0){
            $play_id_list[] = $father_play_info1->father_play_id;
            //$res1 = $this -> where('id', $father_play_info1->father_play_id) -> update($data);
        }

        //判断视频是否存在 父亲id 或者儿子id
        $map = [];
        $map['father_play_id'] = $play_id;
        $father_play_info = $this->where($map)->find();
        if($father_play_info){
            $play_id_list[] = $father_play_info->id;
            //$res1 = $this -> where('id', $father_play_info->id) -> update($data);
        }
        foreach ($play_id_list as $k => $v) {
            $play_id = $v;
            $contact = model('VideoPlayLabelRelation') -> where('play_id', $play_id) -> column('id,label_id');//源标签
            if(!empty($contact)){//删除原有关联标签
                $unlist = [];
                foreach($contact as $key => $value){
                    $unlist[] = $key;
                }
                $rel = model('VideoPlayLabelRelation') -> deleteData($unlist);
                if($rel['code'] != 200){
                    $this->error('错误1' . $rel['message']);
                }
            }
            if($customLabel != ''){//自定义标签插入
                $customLabel_arr = explode(',', $customLabel);
                foreach($customLabel_arr as $value){//区分原有标签，新标签（新标签插入标签表）
                    $label_id = model('VideoPlayClassLabel') -> addDataTage($value);
                    $label[] = $label_id['data'];
                }
            }
            $list = [];
            if(!empty($label)){//关联标签
                foreach($label as $value){
                    $list[] = ['play_id' => $play_id, 'label_id' => $value];
                }
                $rel = model('VideoPlayLabelRelation') -> addDataList($list);
                if($rel['code'] != 200){
                    $this->error('错误2' . $rel['message']);
                }
            }

            $res = $this->useGlobalScope(false) -> where('id', $play_id) -> update($data);
        }

        if($res !== false){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 批量编辑
     * @param play_id int 视频id
     * @param video_classid int 视频分类
     * @author shiqiang
     * @return array_out(code, message)
     */
	public function batchEditData($list){
		$res = $this -> saveAll($list);
        if($res !== false){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 获取视频信息
     * @param int $play_id 视频id
     * @author jason wang <120907037@qq.com>
     * @return info
     */
    public function getInfoByPlayid($play_id, $cache = true){
        $info = self::withJoin('getUcMember,getUcMemberCount', 'LEFT') -> cache($cache)->find($play_id);
        if(!empty($info)){
            return array_out(200, 'success', $info);
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 获取视频信息(纯净)
     * @param int $play_id 视频id
     * @author jason wang <120907037@qq.com>
     * @return info
     */
    public function getPlayinfoByPlayid($play_id, $cache = true){
        $info = $this -> cache($cache)->find($play_id);
        if(!empty($info)){
            return array_out(200, 'success', $info);
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	/**
     * 查询短视频关联的长视频id(如果没关联，返回当前短视频id)
     * @param int $play_id 视频id
     * @author shiqiang
     * @return int
     */
    public function getPlayFatherPlayInfo($play_id, $cache = true){
        $info = $this -> cache($cache)->find($play_id);
        if(!empty($info)){
			if($info -> play_type == 1 && $info -> father_play_id > 0){
				$play_id = $info -> father_play_id;//短视频关联的长视频 PlayID
			}
            return array_out(200, 'success', $play_id);
        }else{
            return array_out(-1001, 'error', 0);
        }
    }
	
	/**
     * 查询长视频关联的短视频
     * @param int $play_id 视频id
     * @author shiqiang
     * @return int
     */
    public function getPlayFatherById($play_id, $cache = true){
        $info = $this -> cache($cache) -> where('father_play_id', $play_id) ->find();
        if(!empty($info)){
            return array_out(200, 'success', $info);
        }else{
            return array_out(-1001, 'error', 0);
        }
    }
	
    /**
     * 评论数增加
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author jason wang <120907037@qq.com>
     * @return bool
     */
    public function incCommentTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setInc('comment_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 评论数减少
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author jason wang <120907037@qq.com>
     * @return bool
     */
    public function decCommentTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setDec('comment_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 点赞增加
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author jason wang <120907037@qq.com>
     * @return bool
     */
    public function incSupportTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setInc('support_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 点赞减少
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author jason wang <120907037@qq.com>
     * @return bool
     */
    public function decSupportTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setDec('support_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	
	 /**
     * 举报增加
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author shiqiang <976162041@qq.com>
     * @return bool
     */
    public function incReportTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setInc('report_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }

    /**
     * 举报减少
     * @param int $play_id 评论id
     * @param int $times 数量（默认1）
     * @author shiqiang <976162041@qq.com>
     * @return bool
     */
    public function decReportTimes($play_id, $times = 1){
        $map = [];
        $map['id'] = $play_id;
        $res = $this -> where($map) -> setDec('report_times', $times);
        if($res){
            return array_out(200, 'success');
        }else{
            return array_out(-1001, 'error');
        }
    }
	
	/*
	 *视频列表
	 * @param int $user_uid 查询的用户id
     * @param int $play_operation_status 视频状态
     * @author jason wang <120907037@qq.com>
     * @return array
	 */
	public function getListByUid($user_uid, $play_operation_status = false){ 
        $map = [];
        $map[] = ['xm_video_play.uid', '=', $user_uid];
        $map[] = ['xm_video_play.play_type', 'in', [1,3]];
        if(is_numeric($play_operation_status)) $map[] = ['xm_video_play.play_operation_status', '=', $play_operation_status];
        $list = self::with('getUcMember,getUcMemberCount,getVideoPlaySupport', 'LEFT') -> where($map) -> order('create_time' ,'desc') -> paginate();
        return array_out(200, 'success', $list);
    }
    
    
    /*
	 * 先拉取近1000条数据 与 推送记录1000条比对
	 * @param int $user_uid 查询的用户id
     * @author jason wang <120907037@qq.com>
     * @return array
	 */
	public function getIndexPushOther1000($user_uid, $play_type, $class_id, $page=1, $page_size = 1000){
        $whereAND = '';
        if($class_id >0 ) $whereAND = " AND video_classid IN (SELECT id FROM xm_video_play_class where pid = ".$class_id.")";
        //查询出 
		$list = model('VideoPlay') -> query(
            "SELECT * FROM `xm_video_play` 
            WHERE `id` NOT IN 
                (SELECT t.play_id FROM (SELECT * FROM `xm_video_play_indexpush` WHERE uid = ".$user_uid." ORDER BY `create_time` DESC LIMIT ".$page.",".$page_size.") as t) 
        AND `play_operation_status` = 1 AND `play_type` = ".$play_type.$whereAND
        );
        return array_out(200, 'success', (array)$list);
    }
    
    /*
	 * 先拉取近1000条数据 与 推送记录1000条比对
	 * @param int $user_uid 查询的用户id
     * @author jason wang <120907037@qq.com>
     * @return array
	 */
	public function getFollowListByUid($uid){

        //查询出 
		$list = model('VideoPlay') -> query("
            SELECT * FROM xm_video_play WHERE uid in 
            (SELECT follow_uid FROM xm_uc_member_follow WHERE uid = ".$uid.") 
            AND id not in(SELECT t.play_id FROM (SELECT * FROM xm_video_play_indexpush where uid = ".$uid." ORDER BY create_time DESC LIMIT 1000) as t)
            AND play_operation_status = 1
            AND play_status = 1
            ORDER BY create_time desc
            limit 1000
            ");
        return array_out(200, 'success', (array)$list);
	}
	
    /**
     * 用户信息 关联载入（一对一）
     */
    public function getUcMember(){
        return $this -> hasOne('app\user_center\model\user\Member','uid', 'uid');
    }

    /**
     * 用户统计 关联载入（一对一）
     */
    public function getUcMemberCount(){
        return $this -> hasOne('app\user_center\model\user\UcMemberCount','uid', 'uid');
    }

    /**
     * 视频审核信息表 关联载入（一对一）
     */
    public function getVideoPlayAiExamine(){
        return $this -> hasOne('app\video\model\VideoPlayAiExamine','play_id', 'id');
    }
	
	/**
     * 是否点赞 关联载入（一对一）
     */
    public function getVideoPlaySupport(){
        return $this -> hasOne('app\video\model\VideoPlaySupport','play_id', 'id');
    }

    /**
     * 视频分类 关联载入（一对一）
     */
    public function getVideoPlayClass(){
        return $this -> hasOne('app\video\model\VideoPlayClass','id', 'video_classid');
    }

}
